<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title></title>

	</head>
	<body>
		<div class="box">
			<input class="searchInput" />
			<ul class="item-wrap"></ul>
		</div>
		
		<script type="text/datas" id="J_datas">
			[
				 {
				 	"name":"张三",
				 	"sex":"male"
				 },
				 {
				 	"name":"张五",
					 "sex":"male"
				 },
				 {
				 	"name":"李四",
					 "sex":"female"
				 }
				]
		</script>
		
		<script type="text/datas" id="tpl">
			<li>{{name}}</li>
		</script>
		
		<script type="text/javascript">
			;(function(doc){
				var data = JSON.parse(doc.getElementById('J_datas').innerHTML),
					tpl = doc.getElementById('tpl').innerHTML,
					oSearchInput = doc.getElementsByClassName('searchInput')[0],
					oWrap = doc.getElementsByClassName('item-wrap')[0];
				
				var init = function(){
					bindEvent();
				}
				
				function bindEvent(){
					oSearchInput.addEventListener('input', debounce(changInput, 500), false);
				}
				
				function changInput(){
					var val = _trimSpace(this.value),
						len = val.length;
						
					if(len) {
						var res = getDatas(val),
							list = []
						res.forEach((item) => {
							console.log(item)
							list += tplReplace(tpl, {'name': item})
						})
						
						oWrap.innerHTML = list
					}else {
						oWrap.innerHTML = ''
					}
				}
				
				function getDatas(val){
					//对数据进行搜索
					return data.reduce((prv, item) => {
						item.name.indexOf(val) !== -1 && prv.push(item.name)
						return prv
					}, [])
					
					//向后端发起请求
					// $.ajax({
					// 	url: xxxxxxxxxxx,
					//     data: val,
					//     success (data) {
					//       resolve(data);
					//     },
					//     error (error) {
					//       alert('网络请求失败');
					//     }
					// });
				}
				
				//去除空格
				function _trimSpace(str){
					return str.replace(/\s+/g, '');
				}
				
				//防抖
				function debounce(fn, time) {
				    let timeout;
				    return function () {
				        let context = this;
				        let args = arguments;
				
				        if (timeout) clearTimeout(timeout);
				        
				        timeout = setTimeout(() => {
				            fn.apply(context, args)
				        }, time);
				    }
				}
				
				//模板替换
				function tplReplace (tpl, replaceObject) {
					return tpl.replace(/{{(.*?)}}/g, (node, key) => {
						return replaceObject[key];
					})
				}
				
				init()
			})(document);
		</script>
	</body>
</html>